package com.csot.ry.controller;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.BiMap;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import com.csot.model.CoarseIp;
import com.csot.model.CoarseSegment;
import com.csot.ry.util.CacheKitUtil;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.ehcache.CacheKit;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.csot.common.annotation.Log;
import com.csot.common.core.controller.BaseController;
import com.csot.common.core.domain.AjaxResult;
import com.csot.common.enums.BusinessType;
import com.csot.ry.domain.TCoarseIp;
import com.csot.ry.service.ITCoarseIpService;
import com.csot.common.utils.poi.ExcelUtil;
import com.csot.common.core.page.TableDataInfo;

/**
 * 粗粒度ip明细Controller
 * 
 * @author 刘沙
 * @date 2022-05-31
 */
@RestController
@RequestMapping("/ipmanagement/coarseip")
public class TCoarseIpController extends BaseController
{
    @Autowired
    private ITCoarseIpService tCoarseIpService;

    public static BiMap<String,String> ip_type = CacheKit.get("dict-data", "ip_type");
    public static BiMap<String,String> ip_city = CacheKit.get("dict-data", "ip_city");
    public static BiMap<String, String> ip_record = CacheKit.get("dict-data", "ip_record");
    public static BiMap<String, String> ip_use_type = CacheKit.get("dict-data", "ip_use_type");
    public static BiMap<String, String> ip_status = CacheKit.get("dict-data", "ip_status");
//    public static BiMap<String, String> ip_dept = CacheKit.get("dict-data", "user-dept");

    /**
     * 查询粗粒度ip明细列表
     */
    @PreAuthorize("@ss.hasPermi('ipmanagement:coarseip:list')")
    @GetMapping("/list/{type}")
    public TableDataInfo list(TCoarseIp tCoarseIp,@PathVariable("type") String type)
    {
        String parentId = getLoginUser().getUser().getDept().getParentId()+"";
        if(CacheKitUtil.ip_dept != null && StrUtil.isNotEmpty(parentId)) {
            tCoarseIp.setIpCity(CacheKitUtil.ip_dept.get(parentId+""));
        }
        tCoarseIp.setIpType(type.toLowerCase());
        startPage();
        List<TCoarseIp> list = tCoarseIpService.selectTCoarseIpList(tCoarseIp);
        return getDataTable(list);
    }

    /**
     * 导出粗粒度ip明细列表
     */
//    @PreAuthorize("@ss.hasPermi('ipmanagement:coarseip:export')")
    @Log(title = "粗粒度ip明细", businessType = BusinessType.EXPORT)
    @PostMapping("/export/{type}")
    public void export(HttpServletResponse response, TCoarseIp tCoarseIp,@PathVariable("type") String type)
    {
        //测试更新子表,TotalSegmentDetail好用了之后删除此方法
//        set1();
        String parentId = getLoginUser().getUser().getDept().getParentId()+"";
        if(CacheKitUtil.ip_dept != null && StrUtil.isNotEmpty(parentId)) {
            tCoarseIp.setIpCity(CacheKitUtil.ip_dept.get(parentId+""));
        }

        List<TCoarseIp> list = tCoarseIpService.selectTCoarseIpList(tCoarseIp);
        for(TCoarseIp t : list){
            t.setIpType(ip_type.get(t.getIpType()));
            t.setIpCity(ip_city.get(t.getIpCity()));
            t.setRecordStatus(ip_record.get(t.getRecordStatus()));
            t.setIpStatus(ip_status.get(t.getIpStatus()));
            t.setIpUseType(ip_use_type.get(t.getIpUseType()));
        }
        ExcelUtil<TCoarseIp> util = new ExcelUtil<TCoarseIp>(TCoarseIp.class);
        util.exportExcel(response, list, "粗粒度ip明细数据");
    }

    private void set1() {
        List<CoarseSegment> csList = getSlot();
        if (CollUtil.isEmpty(csList)) {
            return;
        }

        csList.forEach(f -> {
            ThreadUtil.execute(() -> {
                Db.tx(() -> {
                    List<CoarseIp> ciList = new ArrayList<>();
                    for (long i = f.getIpStartI(); i <= f.getIpEndI(); i++) {
//                        CoarseIp ci = new CoarseIp();
//                        BeanUtil.copyProperties(f, ci, "id");
                        CoarseIp ci = getTotalIpByAll(f);
                        ci.setIpAddressI(i);
                        ci.setIpAddress(NetUtil.longToIpv4(i));
                        ciList.add(ci);
                    }
                    Db.batchSave(ciList, ciList.size());
                    return true;
                });
            });
        });
    }

    public List<CoarseSegment> getSlot() {
        // TODO Auto-generated method stub

        CoarseSegment dao = new CoarseSegment().dao();
        List<CoarseSegment> csList = dao
                .find("select * from t_coarse_segment t where id not IN (select ip_segment_id from t_coarse_ip)");
        return csList;

    }
    private CoarseIp getTotalIpByAll(CoarseSegment f) {
        CoarseIp ci = new CoarseIp();
        ci.setCreateBy(f.getCreateBy());
        ci.setCreateTime(f.getCreateTime());
        ci.setIpCity(f.getIpCity());
        ci.setIpEquipment(f.getIpEquipment());
        ci.setIpGateway(f.getIpGateway());
        ci.setIpManagement(f.getIpManagement());
        ci.setIpSegmentId(f.getId());
        ci.setIpStatus(f.getIpStatus());
        ci.setIpType(f.getIpType());
        ci.setIpUser(f.getIpUser());
        ci.setIpUseType(f.getIpUseType());
        ci.setRecordStatus(f.getRecordStatus());
        ci.setRecordType(f.getRecordType());
        ci.setRemark(f.getRemark());
        ci.setUpdateBy(f.getUpdateBy());
        ci.setUpdateTime(f.getUpdateTime());
        return ci;
    }

    /**
     * 获取粗粒度ip明细详细信息
     */
    @PreAuthorize("@ss.hasPermi('ipmanagement:coarseip:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tCoarseIpService.selectTCoarseIpById(id));
    }

    /**
     * 新增粗粒度ip明细
     */
    @PreAuthorize("@ss.hasPermi('ipmanagement:coarseip:add')")
    @Log(title = "粗粒度ip明细", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TCoarseIp tCoarseIp)
    {
        return toAjax(tCoarseIpService.insertTCoarseIp(tCoarseIp));
    }

    /**
     * 修改粗粒度ip明细
     */
    @PreAuthorize("@ss.hasPermi('ipmanagement:coarseip:edit')")
    @Log(title = "粗粒度ip明细", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TCoarseIp tCoarseIp)
    {
        return toAjax(tCoarseIpService.updateTCoarseIp(tCoarseIp));
    }

    /**
     * 删除粗粒度ip明细
     */
    @PreAuthorize("@ss.hasPermi('ipmanagement:coarseip:remove')")
    @Log(title = "粗粒度ip明细", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tCoarseIpService.deleteTCoarseIpByIds(ids));
    }
}
